const _ = require("./under-dash");

const utils = require("./utils");

// constants
const OPEN_ANGLE = "<";
const CLOSE_ANGLE = ">";
const OPEN_ANGLE_SLASH = "</";
const CLOSE_SLASH_ANGLE = "/>";
const EQUALS_QUOTE = '="';
const QUOTE = '"';
const SPACE = " ";

function pushAttribute(xml, name, value) {
  // 降低数组大小以节省内存
  // 长度为 5N 的所有元素均为 'a' 的数组，占用的内存大于 长度为 N 的所有元素均为 'aaaaa' 的数组
  xml.push(
    SPACE.concat(name, EQUALS_QUOTE, utils.xmlEncode(value.toString()), QUOTE)
  );
  // xml.push(SPACE);
  // xml.push(name);
  // xml.push(EQUALS_QUOTE);
  // xml.push(utils.xmlEncode(value.toString()));
  // xml.push(QUOTE);
}

function pushAttributes(xml, attributes) {
  if (attributes) {
    _.each(attributes, (value, name) => {
      if (value !== undefined) {
        pushAttribute(xml, name, value);
      }
    });
  }
}

/**
 * xml数组超过这个长度时会合并数组内的xml字符。
 * 对于{@link ArrayXml}，数组将会join；对于{@link BufferXml}，数组会在join后写入buffer
 * @type {number}
 */
const preferMergeArrayLength = 500;

class BufferXml {
  constructor() {
    this.offset = 0;
    this.buffer = Buffer.alloc(1024 * 1024 * 2);
    this.array = [];
  }

  _grow() {
    const newBuffer = Buffer.alloc(this.buffer.byteLength + 1024 * 1024 * 2);
    this.buffer.copy(newBuffer, 0, 0, this.offset);
    this.buffer = newBuffer;
    return newBuffer;
  }

  push(str) {
    this.array.push(str);
    if (this.array.length > preferMergeArrayLength) {
      this._write();
    }
  }

  _write() {
    let { buffer } = this;
    const bytes = Buffer.from(this.array.join(""));
    if (bytes.byteLength + this.offset >= this.buffer.byteLength) {
      buffer = this._grow();
    }

    this.offset += bytes.copy(buffer, this.offset, 0);
    this.array = [];
  }

  get value() {
    this._write();
    return this.buffer.subarray(0, this.offset);
  }

  get length() {
    this._write();
    return this.offset;
  }

  removeFrom(pos) {
    // 仅重置offset，后续写入buffer自动覆盖被remove的数据
    this.offset = pos;
    this.array = [];
  }
}

class ArrayXml {
  constructor() {
    this.array = [];
  }

  push(str) {
    this.array.push(str);
    if (this.array.length > preferMergeArrayLength) {
      this.array = [this.array.join("")];
    }
  }

  get value() {
    return this.array.join("");
  }

  get length() {
    return this.array.length;
  }

  removeFrom(pos) {
    this.array.splice(pos, this.array.length - pos);
  }
}

class XmlStream {
  /**
   *
   * @param {boolean=false} useBuffer 是否使用buffer。当要拼接的xml字符较大时应该使用buffer以获取更低的内存占用
   */
  constructor(useBuffer = false) {
    this._xml = useBuffer ? new BufferXml() : new ArrayXml();
    this._stack = [];
    this._rollbacks = [];
  }

  get tos() {
    return this._stack.length ? this._stack[this._stack.length - 1] : undefined;
  }

  get cursor() {
    // handy way to track whether anything has been added
    return this._xml.length;
  }

  openXml(docAttributes) {
    const xml = this._xml;
    // <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    xml.push("<?xml");
    pushAttributes(xml, docAttributes);
    xml.push("?>");
  }

  openNode(name, attributes) {
    const parent = this.tos;
    const xml = this._xml;
    if (parent && this.open) {
      xml.push(CLOSE_ANGLE);
    }

    this._stack.push(name);

    // start streaming node
    xml.push(OPEN_ANGLE + name);
    // xml.push(name);
    pushAttributes(xml, attributes);
    this.leaf = true;
    this.open = true;
  }

  addAttribute(name, value) {
    if (!this.open) {
      throw new Error("Cannot write attributes to node if it is not open");
    }
    if (value !== undefined) {
      pushAttribute(this._xml, name, value);
    }
  }

  addAttributes(attrs) {
    if (!this.open) {
      throw new Error("Cannot write attributes to node if it is not open");
    }
    pushAttributes(this._xml, attrs);
  }

  writeText(text) {
    const xml = this._xml;
    if (this.open) {
      xml.push(CLOSE_ANGLE);
      this.open = false;
    }
    this.leaf = false;
    xml.push(utils.xmlEncode(text.toString()));
  }

  append(text) {
    this._xml.push(text);
  }

  writeXml(xml) {
    if (this.open) {
      this._xml.push(CLOSE_ANGLE);
      this.open = false;
    }
    this.leaf = false;
    this._xml.push(xml);
  }

  closeNode() {
    const node = this._stack.pop();
    const xml = this._xml;
    if (this.leaf) {
      xml.push(CLOSE_SLASH_ANGLE);
    } else {
      xml.push(OPEN_ANGLE_SLASH + node + CLOSE_ANGLE);
      // xml.push(node);
      // xml.push(CLOSE_ANGLE);
    }
    this.open = false;
    this.leaf = false;
  }

  leafNode(name, attributes, text) {
    this.openNode(name, attributes);
    if (text !== undefined) {
      // zeros need to be written
      this.writeText(text);
    }
    this.closeNode();
  }

  closeAll() {
    while (this._stack.length) {
      this.closeNode();
    }
  }

  addRollback() {
    this._rollbacks.push({
      xml: this._xml.length,
      stack: this._stack.length,
      leaf: this.leaf,
      open: this.open,
    });
    return this.cursor;
  }

  commit() {
    this._rollbacks.pop();
  }

  rollback() {
    const r = this._rollbacks.pop();
    this._xml.removeFrom(r.xml);
    this._stack.splice(r.stack, this._stack.length - r.stack);
    this.leaf = r.leaf;
    this.open = r.open;
  }

  get xml() {
    this.closeAll();
    return this._xml.value;
  }
}

XmlStream.StdDocAttributes = {
  version: "1.0",
  encoding: "UTF-8",
  standalone: "yes",
};

module.exports = XmlStream;
